package chinatelecom.feilong.framework.web.sys.controller;

import chinatelecom.feilong.framework.common.global.Global;
import chinatelecom.feilong.framework.common.util.FileUploadUtils;
import chinatelecom.feilong.framework.web.sys.entity.Dictionary;
import chinatelecom.feilong.framework.web.sys.service.IDictionaryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hnayan on 2017/9/4.
 */
@Controller
@RequestMapping("/sys/system/")
public class SystemConfigController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemConfigController.class);

    @Resource
    private IDictionaryService iDictionaryService;
    /***
     * 跳转到系统配置列表页面
     * @return bdspDictionary
     */
    @RequestMapping("logo_change")
    public String config_list(Model model) {
        //自定义的logo信息
        Dictionary logoText = iDictionaryService.findByCode("logoText");
        model.addAttribute("logoText", logoText != null ?
                logoText.getName() : Global.getProperty("defaultLogoText"));
        Dictionary rightText = iDictionaryService.findByCode("rightText");
        model.addAttribute("rightText", rightText != null ?
                rightText.getName() : Global.getProperty("defaultCopyRight"));
        return "modules/sys/system/logo_change";
    }

    /***
     * 异步拉取系统配置列表
     * @param rows
     * @param page
     * @param sortName
     * @param sortValue
     * @return
     */
    @RequestMapping(value="ajax_config_data")
    @ResponseBody
    public Map ajaxConfigData(HttpServletRequest request,Integer rows,Integer page,String sortName,String sortValue){
        Integer pageSize = rows==null?10:rows;
        Integer curPage = page==null?0:page-1;
        Map<String,Object> searchParams = new HashMap<String, Object>();
        String code = request.getParameter("code");
        if(StringUtils.isNotBlank(code)){
            searchParams.put("LIKE_code",code);
        }
        searchParams.put("EQ_isDelete", 0);
        Pageable pageable = new PageRequest(curPage, pageSize);
        Page<Dictionary> userPage = iDictionaryService.findConfigPageByParams(searchParams,pageable,sortName,sortValue);
        Map data = new HashMap();
        data.put("total",userPage.getTotalElements());
        data.put("rows",userPage.getContent());
        return  data;
    }

    /***
     * 跳转到系统配置添加页面
     * @param id
     * @return bdspDictionary
     */
    @RequestMapping(value="config_add")
    public String configAdd(@RequestParam(required=false) String id,Model model){
        if(StringUtils.isNotEmpty(id)){
            Dictionary dictionary = iDictionaryService.findOneBdspDictionary(Integer.valueOf(id));
            model.addAttribute("bdspDictionary", dictionary);
        }
        return "modules/sys/system/config_add";
    }

    /***
     * 跳转到系统配置资源添加页面
     * @param id
     * @return bdspDictionary
     */
    @RequestMapping(value="config_resource_add")
    public String configResourceAdd(@RequestParam(required=false) String id,Model model){
        if(StringUtils.isNotEmpty(id)){
            Dictionary dictionary = iDictionaryService.findOneBdspDictionary(Integer.valueOf(id));
            model.addAttribute("bdspDictionary", dictionary);
        }
        return "modules/sys/system/config_resource_add";
    }

    /**
     * 添加资源方法
     * @param logoImg
     * @param logoName
     * @param rightsText
     * @return JSONObject 保存成功返回路径和成功状态，保存失败返回失败状态
     */
    @RequestMapping("save_infos")
    public String changeLogo(MultipartFile logoImg, String logoName, String rightsText, RedirectAttributes redirectAttributes) {
        //保存路径
        String filePath = Global.getProperty("logoImgPath");
        File uploadDir = new File(filePath);
        boolean isSuccess = false;
        if (!uploadDir.exists() || !uploadDir.isDirectory()) {
            isSuccess = uploadDir.mkdirs();
        }
        try {
            FileUploadUtils fileUploadUtils = new FileUploadUtils();
            //存到本地路径
            isSuccess = fileUploadUtils.fileUpload(logoImg, logoImg.getContentType(), logoImg.getOriginalFilename(), uploadDir.toString());
            //存入数据库
            Dictionary dictionary = new Dictionary();
            dictionary.setName(filePath + "/" + logoImg.getOriginalFilename());
            dictionary.setCode("logoImgPath");
            dictionary.setIsDelete(0);
            iDictionaryService.saveDictionariesByCode(dictionary,"logoImgPath");
        } catch (IOException e) {
            LOGGER.error("保存图片失败");
        }
        Dictionary logoText = new Dictionary();
        logoText.setCode("logoText");
        logoText.setName(logoName);
        logoText.setIsDelete(0);
        iDictionaryService.saveDictionariesByCode(logoText, "logoText");

        Dictionary rightText = new Dictionary();
        rightText.setCode("rightText");
        rightText.setName(rightsText);
        rightText.setIsDelete(0);
        iDictionaryService.saveDictionariesByCode(rightText, "rightText");
        if (isSuccess) {
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } else {
            redirectAttributes.addFlashAttribute("message", "保存失败");
        }
        return "redirect:logo_change";
    }

    /***
     * 保存一条dictionary信息
     * @param dictionary
     * @return bdspDictionary
     */
    @RequestMapping("config_save")
    public String configSave(Dictionary dictionary, RedirectAttributes redirectAttributes) {
        try {
            iDictionaryService.saveDictionariesByCode(dictionary, dictionary.getCode());
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        }catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败");
        }
        return "redirect:config_add?id="+ dictionary.getId();
    }

    /***
     * 批量删除
     * @param idStr
     * @return
     */
    @RequestMapping("config_delete")
    @ResponseBody
    public Integer configDelete(@RequestParam String idStr){
        Integer result = 0;
        try{
            String[] ids = idStr.split(",");
            iDictionaryService.deleteDictionariesByIds(ids);
        }catch(Exception e){
            LOGGER.error("删除失败",e);
            result = 1;
        }
        return result;
    }

    /***
     * 返回图片信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "logo_img")
    public void getLogoImg(HttpServletRequest request, HttpServletResponse response) {
        Dictionary logoDictionary = iDictionaryService.findByCode("logoImgPath");
        File file;
        if (logoDictionary != null) {
            file = new File(logoDictionary.getName());
            if (!(file.exists() && file.canRead())) {
                file = Global.getWebResource(Global.getProperty("defaultLogoPath"));
            }
        } else {
            file = Global.getWebResource(Global.getProperty("defaultLogoPath"));
        }
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            try {
                int length = inputStream.read(data);
                inputStream.close();
                response.setContentType("image/png");
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

//    @ResponseBody
//    @RequestMapping("save_logo")
//    public Integer saveLogo(MultipartFile file) {
//        Integer ret;
//        String filePath = logoImgPath;
//        File uploadDir = new File(filePath);
//        boolean isSuccess = false;
//        if (!uploadDir.exists() || !uploadDir.isDirectory()) {
//            isSuccess = uploadDir.mkdirs();
//        }
//        try {
//            FileUploadUtils fileUploadUtils = new FileUploadUtils();
//            //存到本地路径
//            isSuccess = fileUploadUtils.fileUpload(file, file.getContentType(), file.getOriginalFilename(), uploadDir.toString());
//            //存入数据库
//            Dictionary dictionary = new Dictionary();
//            dictionary.setName(filePath + "/" + file.getOriginalFilename());
//            dictionary.setCode("logoImgPath");
//            dictionary.setIsDelete(0);
//            iDictionaryService.saveDictionariesByCode(dictionary, "logoImgPath");
//        } catch (IOException e) {
//            LOGGER.error("保存图片失败");
//        }
//        if (isSuccess) {
//            ret = 0;
//        } else {
//            ret = 1;
//        }
//        return ret;
//    }
}
